# -*- coding: utf-8 -*-
import logging

from common.lottery import LOTTERY_TYPE
from common.lottery.db import create_track_index
from common.lottery.cyclical import TRACK_STATUS, ORDER_TYPE
from common.lottery.cyclical.sd_11x5.db import order as db
from common.lottery.cyclical.sd_11x5.logic import order as logic
from common.lottery.cyclical.sd_11x5.logic.activity import xrange_term
from common.utils import exceptions as err
from common.utils.id_generator import generate_long_id
from common.utils.api import check_params, parse_unit
from common.lottery.cyclical.sd_11x5.model.order import BET_TYPE

_LOGGER = logging.getLogger(__name__)


def check_order_params(item):
    '''数据层面校验订单合法性
    '''
    check_params(item, ['term', 'number', 'bet_type'], {
        'times': 1, 'term_count': 1, 'type': 1, 'unit': 2})

    for k in 'times', 'term_count', 'bet_type', 'type':
        item[k] = int(item[k])
    item['unit'] = parse_unit(item['unit'])
    if (item['times'] < 1 or item['term_count'] < 1 or
            item['bet_type'] not in BET_TYPE.values() or
            item['bet_type'] == BET_TYPE.ONE_ANY or
            item['type'] not in ORDER_TYPE.values()):
        raise err.ParamError('param illegal')
    try:
        logic.valid_number(item['bet_type'], item['number'])
    except Exception as e:
        raise err.ParamError(e)


def create_order(user_id, info, context=None):
    info['user_id'] = user_id
    info['extend'] = context
    info['price'] = logic.calc_total_price(info['bet_type'],
                                           info['number'], info['times'],
                                           info['unit'])
    count = info.pop('term_count')
    if count == 1:
        info['type'] = ORDER_TYPE.NORMAL
        db.OrderPayer.pay(info)
        return info['price'] / info['unit'] / info['times'], info['price']
    else:  # 追号，可能数据量较大，需要优化
        start_term = info['term']
        info['track_id'] = generate_long_id('track_id')
        has_order = False
        succ_count, succ_amount, tracked_count, tracked_amount = 0, 0, 0, 0
        for term in xrange_term(start_term, count):
            info['term'] = term
            try:
                order = db.OrderPayer.pay(info)
                if order:
                    has_order = True
                    succ_count += 1
                    succ_amount += order.price
                    if order.track_status == TRACK_STATUS.TRACKED:
                        tracked_count += 1
                        tracked_amount += order.price
            except err.TermExpired:
                # 对于追号，如果已经开了，就跳过这一期
                pass
            except Exception as e:
                _LOGGER.exception('sd_11x5 order pay error, %s', e)
        if has_order:
            create_track_index(LOTTERY_TYPE.SD_11X5, user_id, info['track_id'],
                               succ_count, succ_amount, tracked_count, tracked_amount)
        return count, info['price'] * count
